﻿using System;
using System.IO.IsolatedStorage;
using VXCompany.SilverlightLogging.ServiceProxy;

namespace VXCompany.SilverlightLogging.MVVM.Models
{

	/// <summary>
	/// Contains Config values. (from service or default.)
	/// </summary>
	public class Configuration : MVVM.Models.NotifyingBase
	{
		#region Fields

		private const string STORAGE_KEY = "Q23fSADFSAeswsewseF";

		private bool _isInit = false;

		#endregion Fields

		#region Constructors

		/// <summary>
		/// Creates new instance.
		/// </summary>
		public Configuration()
		{

		}

		#endregion Constructors

		#region Events

		/// <summary>
		/// Fires when new config info is received.
		/// </summary>
		public event EventHandler ConfigurationChanged;

		#endregion Events

		#region Properties

		/// <summary>
		/// Contains the actual config values.
		/// </summary>
		public LoggingConfigurationMessage ConfigurationValues
		{
			get;
			private set;
		}

		/// <summary>
		/// Indicates whether configuration is available. 
		/// </summary>
		public bool IsConfigurationAvailable
		{
			get;
			private set;
		}

		#endregion Properties

		#region Methods

		/// <summary>
		/// Calls config service.
		/// </summary>
		public void Initialize(LoggingServiceClient client)
		{
			if (!_isInit)
			{
				IsConfigurationAvailable = true;
				ConfigurationValues = GetConfigurationValuesFromStorage();
				if (ConfigurationValues == null)
				{
					GetDefaultConfigurationValues();
					OnConfigurationChanged();
					StoreConfig();
				}
				client.GetClientConfigCompleted += (sender, e) =>
					{
						if (e.Error == null)
						{
							ConfigurationValues = e.Result;
							StoreConfig();
							OnConfigurationChanged();
						}
						else
						{
							IsConfigurationAvailable = false;
						}
					};
				client.GetClientConfigAsync();
				_isInit = true;
			}
		}

		/// <summary>
		/// Fires the ConfigurationChanged event.
		/// </summary>
		private void OnConfigurationChanged()
		{
			if (ConfigurationChanged != null)
			{
				ConfigurationChanged(null, EventArgs.Empty);
			}
		}

		/// <summary>
		/// Returns default configuration values.
		/// </summary>
		private void GetDefaultConfigurationValues()
		{
			ConfigurationValues = new LoggingConfigurationMessage { SyncBehaviorFlags = SyncBehaviorFlags.AppStart | SyncBehaviorFlags.AppCrash, MinLogLevel = ErrorLevel.Informational, MinSyncLevel = ErrorLevel.Informational };
		}

		/// <summary>
		/// Attempts to get config from store.
		/// </summary>
		/// <returns></returns>
		private LoggingConfigurationMessage GetConfigurationValuesFromStorage()
		{
			LoggingConfigurationMessage config = null;
			try
			{
				if (!IsConfigurationAvailable && IsolatedStorageSettings.ApplicationSettings.Contains(STORAGE_KEY))
				{
					config = (LoggingConfigurationMessage)IsolatedStorageSettings.ApplicationSettings[STORAGE_KEY];
				}
			}
			catch (IsolatedStorageException)
			{
				IsConfigurationAvailable = false;
			}
			return config;
		}

		/// <summary>
		/// Attempts to store config in local storage.
		/// </summary>
		private void StoreConfig()
		{
			if (!IsConfigurationAvailable)
			{
				return;
			}
			try
			{
				IsolatedStorageSettings.ApplicationSettings[STORAGE_KEY] = ConfigurationValues;
				IsolatedStorageSettings.ApplicationSettings.Save();
			}
			catch (IsolatedStorageException)
			{
				IsConfigurationAvailable = false;
			}
		}

		#endregion Methods
	}
}